package com.jk.myimkit.imkit.plugin.location;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.jk.myimkit.R;
import com.jk.myimkit.imkit.RongBaseActivity;

import io.rong.common.RLog;

public class AMapLocationActivity extends RongBaseActivity implements LocationSource, AMap.OnCameraChangeListener, GeocodeSearch.OnGeocodeSearchListener, IMyLocationChangedListener {
    private static final String TAG = "AMapLocationActivity";
    private static final int REQUEST_CODE_ASK_PERMISSIONS = 100;
    private BitmapDescriptor mBitmapDescriptor;
    private MapView mAMapView;
    private AMap mAMap;
    private TextView mLocationTip;
    private Handler mHandler;
    private Marker mMarker;
    private GeocodeSearch mGeocodeSearch;
    private OnLocationChangedListener mLocationChangedListener;
    private double mMyLat;
    private double mMyLng;
    private String mMyPoi;
    private double mLatResult;
    private double mLngResult;
    private String mPoiResult;
    ValueAnimator animator;

    public AMapLocationActivity() {
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.rc_plugin_location_activity);
        this.mAMapView = (MapView)this.findViewById(R.id.rc_ext_amap);
        this.mHandler = new Handler();
        this.mLocationTip = (TextView)this.findViewById(R.id.rc_ext_location_marker);
        this.findViewById(R.id.rc_ext_my_location).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (AMapLocationActivity.this.mMyPoi != null) {
                    AMapLocationActivity.this.mAMap.setOnCameraChangeListener((AMap.OnCameraChangeListener)null);
                    CameraUpdate update = CameraUpdateFactory.changeLatLng(new LatLng(AMapLocationActivity.this.mMyLat, AMapLocationActivity.this.mMyLng));
                    AMapLocationActivity.this.mAMap.animateCamera(update, new AMap.CancelableCallback() {
                        public void onFinish() {
                            AMapLocationActivity.this.mAMap.setOnCameraChangeListener(AMapLocationActivity.this);
                        }

                        public void onCancel() {
                        }
                    });
                    AMapLocationActivity.this.mLocationTip.setText(AMapLocationActivity.this.mMyPoi);
                    AMapLocationActivity.this.mLatResult = AMapLocationActivity.this.mMyLat;
                    AMapLocationActivity.this.mLngResult = AMapLocationActivity.this.mMyLng;
                    AMapLocationActivity.this.mPoiResult = AMapLocationActivity.this.mMyPoi;
                } else {
                    LocationManager.getInstance().updateMyLocation();
                }

            }
        });
        View ok = this.findViewById(R.id.rc_action_bar_ok);
        ok.setVisibility(View.VISIBLE);
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (AMapLocationActivity.this.mLatResult == 0.0D && AMapLocationActivity.this.mLngResult == 0.0D && TextUtils.isEmpty(AMapLocationActivity.this.mPoiResult)) {
                    Toast.makeText(AMapLocationActivity.this, AMapLocationActivity.this.getString(R.string.rc_location_temp_failed), Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("thumb", AMapLocationActivity.this.getMapUrl(AMapLocationActivity.this.mLatResult, AMapLocationActivity.this.mLngResult));
                    intent.putExtra("lat", AMapLocationActivity.this.mLatResult);
                    intent.putExtra("lng", AMapLocationActivity.this.mLngResult);
                    intent.putExtra("poi", AMapLocationActivity.this.mPoiResult);
                    AMapLocationActivity.this.setResult(-1, intent);
                    AMapLocationActivity.this.finish();
                }
            }
        });
        TextView title = (TextView)this.findViewById(R.id.rc_action_bar_title);
        title.setText(R.string.rc_plugin_location);
        this.mAMapView.onCreate(savedInstanceState);
        this.initMap();
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch(requestCode) {
            case 100:
                if (grantResults[0] == 0 && permissions[0].equals("android.permission.ACCESS_COARSE_LOCATION")) {
                    this.initMap();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    private void initMap() {
        this.mAMap = this.mAMapView.getMap();
        this.mAMap.setLocationSource(this);
        this.mAMap.setMyLocationEnabled(true);
        this.mAMap.getUiSettings().setZoomControlsEnabled(false);
        this.mAMap.getUiSettings().setMyLocationButtonEnabled(false);
        this.mAMap.setMapType(1);
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.rc_ext_my_locator));
        myLocationStyle.strokeWidth(0.0F);
        myLocationStyle.strokeColor(R.color.rc_main_theme);
        myLocationStyle.radiusFillColor(0);
        this.mAMap.setMyLocationStyle(myLocationStyle);
        this.mGeocodeSearch = new GeocodeSearch(this);
        this.mGeocodeSearch.setOnGeocodeSearchListener(this);
        LocationManager.getInstance().setMyLocationChangedListener(this);
    }

    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RLog.d("AMapLocationActivity", "onRegeocodeSearched");
        if (regeocodeResult != null) {
            RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
            this.mLatResult = regeocodeResult.getRegeocodeQuery().getPoint().getLatitude();
            this.mLngResult = regeocodeResult.getRegeocodeQuery().getPoint().getLongitude();
            String formatAddress = regeocodeResult.getRegeocodeAddress().getFormatAddress();
            this.mPoiResult = formatAddress.replace(regeocodeAddress.getProvince(), "").replace(regeocodeAddress.getCity(), "").replace(regeocodeAddress.getDistrict(), "");
            this.mLocationTip.setText(this.mPoiResult);
            LatLng latLng = new LatLng(this.mLatResult, this.mLngResult);
            if (this.mMarker != null) {
                this.mMarker.setPosition(latLng);
            }
        } else {
            Toast.makeText(this, this.getString(R.string.rc_location_fail), Toast.LENGTH_SHORT).show();
        }

    }

    private String getMapUrl(double latitude, double longitude) {
        return "http://restapi.amap.com/v3/staticmap?location=" + longitude + "," + latitude + "&zoom=16&scale=2&size=408*240&markers=mid,,A:" + longitude + "," + latitude + "&key=e09af6a2b26c02086e9216bd07c960ae";
    }

    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
    }

    public void activate(OnLocationChangedListener onLocationChangedListener) {
        this.mLocationChangedListener = onLocationChangedListener;
    }

    public void deactivate() {
    }

    public void onCameraChange(CameraPosition cameraPosition) {
        RLog.d("AMapLocationActivity", "onCameraChange");
        if (Build.VERSION.SDK_INT < 11) {
            this.mMarker.setPosition(cameraPosition.target);
        }

    }

    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        RLog.d("AMapLocationActivity", "onCameraChangeFinish");
        LatLonPoint point = new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude);
        RegeocodeQuery query = new RegeocodeQuery(point, 50.0F, "autonavi");
        this.mGeocodeSearch.getFromLocationAsyn(query);
        if (this.mMarker != null) {
            this.animMarker();
        }

    }

    private void addLocatedMarker(LatLng latLng, String poi) {
        this.mBitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.rc_ext_location_marker);
        MarkerOptions markerOptions = (new MarkerOptions()).position(latLng).icon(this.mBitmapDescriptor);
        if (this.mMarker != null) {
            this.mMarker.remove();
        }

        this.mMarker = this.mAMap.addMarker(markerOptions);
        this.mMarker.setPositionByPixels(this.mAMapView.getWidth() / 2, this.mAMapView.getHeight() / 2);
        this.mLocationTip.setText(String.format("%s", poi));
    }

    @TargetApi(11)
    private void animMarker() {
        if (Build.VERSION.SDK_INT > 11) {
            if (this.animator != null) {
                this.animator.start();
                return;
            }

            this.animator = ValueAnimator.ofFloat(new float[]{(float)(this.mAMapView.getHeight() / 2), (float)(this.mAMapView.getHeight() / 2 - 30)});
            this.animator.setInterpolator(new DecelerateInterpolator());
            this.animator.setDuration(150L);
            this.animator.setRepeatCount(1);
            this.animator.setRepeatMode(ValueAnimator.REVERSE);
            this.animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                public void onAnimationUpdate(ValueAnimator animation) {
                    RLog.d("AMapLocationActivity", "onAnimationUpdate");
                    Float value = (Float)animation.getAnimatedValue();
                    AMapLocationActivity.this.mMarker.setPositionByPixels(AMapLocationActivity.this.mAMapView.getWidth() / 2, Math.round(value));
                }
            });
            this.animator.addListener(new AnimatorListenerAdapter() {
                public void onAnimationEnd(Animator animation) {
                    AMapLocationActivity.this.mMarker.setIcon(AMapLocationActivity.this.mBitmapDescriptor);
                }
            });
            this.animator.start();
        }

    }

    protected void onDestroy() {
        this.mAMapView.onDestroy();
        LocationManager.getInstance().setMyLocationChangedListener((IMyLocationChangedListener)null);
        super.onDestroy();
    }

    public void onMyLocationChanged(final AMapLocationInfo locationInfo) {
        RLog.d("AMapLocationActivity", "onLocationChanged");
        if (this.mLocationChangedListener != null) {
            this.mHandler.post(new Runnable() {
                public void run() {
                    if (locationInfo != null) {
                        AMapLocationActivity.this.mMyLat = AMapLocationActivity.this.mLatResult = locationInfo.getLat();
                        AMapLocationActivity.this.mMyLng = AMapLocationActivity.this.mLngResult = locationInfo.getLng();
                        AMapLocationActivity.this.mMyPoi = AMapLocationActivity.this.mPoiResult = locationInfo.getStreet() + locationInfo.getPoiname();
                        Location location = new Location("AMap");
                        location.setLatitude(locationInfo.getLat());
                        location.setLongitude(locationInfo.getLng());
                        location.setTime(locationInfo.getTime());
                        location.setAccuracy(locationInfo.getAccuracy());
                        AMapLocationActivity.this.mLocationChangedListener.onLocationChanged(location);
                        AMapLocationActivity.this.addLocatedMarker(new LatLng(AMapLocationActivity.this.mLatResult, AMapLocationActivity.this.mLngResult), AMapLocationActivity.this.mPoiResult);
                        CameraUpdate update = CameraUpdateFactory.zoomTo(17.0F);
                        AMapLocationActivity.this.mAMap.animateCamera(update, new AMap.CancelableCallback() {
                            public void onFinish() {
                                AMapLocationActivity.this.mAMap.setOnCameraChangeListener(AMapLocationActivity.this);
                            }

                            public void onCancel() {
                            }
                        });
                    } else {
                        Toast.makeText(AMapLocationActivity.this, AMapLocationActivity.this.getString(R.string.rc_location_fail), Toast.LENGTH_SHORT).show();
                    }

                }
            });
        }

    }
}